/**
 * Copyright (C), 2020-2021 by colley.ma
 * File Name: RefreshRate.java
 * Encoding: UTF-8
 * Date: 2021年4月21日 下午3:03:57
 * History:
 */
package com.swak.frame.job;

import java.text.ParseException;
import java.util.Date;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.quartz.CronExpression;

public class RefreshRate {

    public CronExpression cronExpr;

    public long fixedRate;

    public TimeUnit unit;

    public RefreshRate(String cron, long fixedRate) {
        if (StringUtils.isNoneEmpty(cron)) {
            try {
                this.cronExpr = new CronExpression(cron);
            } catch (ParseException e) {
            }
        }
        this.fixedRate = fixedRate;
        this.unit = TimeUnit.SECONDS;
    }

    public RefreshRate(String cron, long fixedRate, TimeUnit unit) {
        this(cron, fixedRate);
        this.unit = Optional.ofNullable(unit).orElse(TimeUnit.SECONDS);
    }

    public long getRate() {
        long nextPeriod = 0;
        if (cronExpr != null) {
            Date nextDate = cronExpr.getNextValidTimeAfter(new Date());
            nextPeriod = nextDate.getTime() - System.currentTimeMillis();
        }
        return nextPeriod > 0 ? TimeUnit.MILLISECONDS.toSeconds(nextPeriod)
            : unit.toSeconds(fixedRate);
    }

    /**
     * 分布式缓存时间
     * 
     * @param @param distributedPeriod
     * @param @return
     * @return long
     */
    public long getDistributedRate(long distributedPeriod) {
        // 如果是 CronExpression任务，缓存时间动态计算
        if (cronExpr != null) {
            long peroid = getRate();
            return Math.max((peroid - 3), 30);
        }
        return distributedPeriod;
    }
}
